package com.empire.module.member.utils;

import org.docx4j.convert.in.xhtml.XHTMLImporterImpl;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.wml.RFonts;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.util.StringUtils;

import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 类名：WordUtil
 * 描述：
 * 时间：2020/6/5 17:23
 *
 * @author WangYu
 * @version 1.0
 */
public class WordUtil {
    public static void htmlToWord(File file, File wordFile) {
        try {
            Document doc = Jsoup.parse(file, "utf-8");
            List<Element> list = doc.getAllElements();
            String html = "";
            for (Element element : list) {
                if (element.tagName().equals("#root")) {
                    html = element.toString().replace("<!doctype html>", "");
                }
                String str = element.toString();
                if (element.tagName().equals("meta")
                        || element.tagName().equals("img")
                        || element.tagName().equals("br")
                        || element.tagName().equals("input")
                        || element.tagName().equals("link")) {
                    if (!str.endsWith("/>")) {
                        String elementStr = element.toString();
                        if (element.tagName().equals("img")) {
                            String width = element.attr("width");
                            if (StringUtils.isEmpty(width)) {
                                element.attr("width", "321");
                            } else {
                                Integer wid = Integer.parseInt(width);
                                if (wid > 321) {
                                    element.attr("width", "321");
                                }
                            }
                            str = element.toString().replace(">", "></img>");
                        } else if (element.tagName().equals("meta")) {
                            str = str.replace(">", "></meta>");
                        } else {
                            str = str.replace(">", "/>");
                        }
                        html = html.replace(elementStr, str);
                    }
                }
            }
            // Setup font mapping
            RFonts rfonts = Context.getWmlObjectFactory().createRFonts();
            rfonts.setAscii("Century Gothic");
            XHTMLImporterImpl.addFontMapping("Century Gothic", rfonts);

            // Create an empty docx package
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

            NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
            wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
            ndp.unmarshalDefaultNumbering();

            // Convert the XHTML, and add it into the empty docx we made
            XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);

            XHTMLImporter.setHyperlinkStyle("Hyperlink");
            wordMLPackage.getMainDocumentPart().getContent().addAll(
                    XHTMLImporter.convert(html, null));

            wordMLPackage.save(wordFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (Docx4JException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        /*try {
            XWPFDocument doc = new XWPFDocument();
            XWPFRun run = doc.createParagraph().createRun();
            run.setText("2222");
            run.setSubscript(VerticalAlign.SUBSCRIPT);
            run.setTextPosition(100);
            run.setColor("FF1493");
            XWPFRun run2 = doc.createParagraph().createRun();
            run2.setText("21");
            run2.setSubscript(VerticalAlign.BASELINE);
            run2.setTextPosition(100);
            run2.setColor("FF1493");
            XWPFRun run3 = doc.createParagraph().createRun();
            run3.setText("23");
            run3.setSubscript(VerticalAlign.SUPERSCRIPT);
            run3.setTextPosition(100);
            run3.setColor("FF1493");
            XWPFTableRow row = doc.createTable().getRow(0);
            row.getCell(0).setText("111");
            row.getCell(0).setColor("FF1493");
            row.getCell(0).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            XWPFTableCell cell = row.addNewTableCell();
            cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(200));
            cell.setText("333");
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            XWPFRun run1 = doc.createParagraph().createRun();
            File file = new File("C:\\Users\\yu wang\\Pictures\\Saved Pictures\\1.jpg");
            BufferedImage img = ImageIO.read(file);
            run1.addPicture(new FileInputStream(file),
                    Document.PICTURE_TYPE_JPEG,"",
                    Units.pixelToEMU(img.getWidth()),Units.pixelToEMU(img.getHeight()));
            FileOutputStream out = new FileOutputStream(new File("E:\\word.docx"));
            doc.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }*/


    }
}
